<template>
  <ProjectInfo
    :projectId="`${route.query.projectId}`"
    :reportType="'IIKC'"
    :sign="true"
    :sync="true"
    :sync-content="'从现场采样同步信息'"
    :preview="true"
    @preview-file="onPreviewHeader"
    @on-sync-header="onSyncHeader"
  />

  <ContentWrap class="chem-record-wrap">
    <div class="header-container-consumable">
      <!-- Title Centered -->
      <h2 class="centered-title-consumable">工作场所空气中粉尘测定记录表</h2>
    </div>
    <!-- 头部信息表单 -->
    <el-form :model="form" class="chem-form" label-width="100px">
      <el-row :gutter="24" align="middle">
        <el-col :span="3">
          <el-form-item label="样品名称">
            <el-input v-model.lazy="form.sampleName" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="空气收集器">
            <el-input v-model.lazy="form.airCollector" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="砝码标准值(g)">
            <el-input v-model.lazy="form.fmbzz" placeholder="请输入标准砝码标准值" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="仪器信息">
            <el-input
              v-model.lazy="form.instrumentInfo"
              placeholder="双击选择"
              readonly
              @dblclick="openFacilityDialog()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测依据">
            <el-input-tag v-model="form.testBasis" placeholder="请输入检测依据" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" align="middle">
        <el-col :span="3">
          <el-form-item label="气温(℃)">
            <el-input v-model.lazy="form.temperature" placeholder="请输入气温" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="湿度(%RH)">
            <el-input v-model.lazy="form.humidity" placeholder="请输入湿度" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="砝码称量质量(g)">
            <el-input v-model.lazy="form.fmclz" placeholder="请输入标准砝码称量质量" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="送检日期">
            <el-date-picker
              v-model.lazy="form.submissionDate"
              placeholder="选择送检日期"
              style="width: 100%"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测日期">
            <el-date-picker
              v-model.lazy="form.testDate"
              placeholder="选择检测日期"
              style="width: 100%"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" align="middle">
        <el-col :span="6">
          <el-form-item label="定量下限(mg)">
            <el-input v-model.lazy="form.dlxx" placeholder="请选择仪器信息" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="最低定量浓度">
            <el-input
              v-model.lazy="form.zddlld"
              placeholder="双击设置最低定量浓度"
              readonly
              @dblclick="minimumQuantitativeConcentration"
            >
              <template #suffix>
                <span
                  style="color: #999; font-size: 13px; cursor: pointer; user-select: none"
                  @dblclick.stop="minimumQuantitativeConcentration"
                  >双击设置最低定量浓度</span
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe table-layout="fixed">
      <el-table-column align="center" label="序号" type="index" />
      <el-table-column align="center" label="样品编号" prop="sampleNo">
        <template #default="{ row }">
          <el-input v-model.lazy="row.sampleNo" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样体积（L）" prop="volume">
        <template #default="{ row }">
          <el-input v-model.lazy="row.sampleVolume" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="滤膜编号" prop="cllmbh">
        <template #default="{ row }">
          <el-input v-model.lazy="row.cllmbh" placeholder="" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样前滤膜质量m₁(g)" prop="quality">
        <template #default="{ row }">
          <el-input v-model.lazy="row.quality" placeholder="" @input="onWeightInput(row)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样后滤膜质量m₂(g)" prop="postWeight">
        <template #default="{ row }">
          <el-input
            v-model.lazy="row.postWeight"
            placeholder=""
            @focus="row._oldPostWeight = row.postWeight"
            @blur="onPostWeightInput(row, row._oldPostWeight)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="滤膜增重m(g)" prop="weightIncrease">
        <template #default="{ row }">
          <el-input v-model.lazy="row.weightIncrease" placeholder="" readonly />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测定结果(mg/m³)" prop="result">
        <template #default="{ row }">
          <el-input :model-value="getResultValue(row)" placeholder="" readonly />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <el-dialog
    v-model.lazy="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :default-status="1"
        :show-selection="false"
        @selection-change="handleFacilitySelectionChange"
        @handle-facility-confirm="handleFacilityConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="minQuantDialogVisible"
    append-to-body
    draggable
    title="最低定量浓度"
    width="600px"
  >
    <div style="margin-bottom: 10px; display: flex; justify-content: flex-start">
      <el-button type="primary" @click="addMinQuantRow">添加</el-button>
    </div>
    <el-table :data="form.minQuantTable" border style="margin-bottom: 0">
      <el-table-column align="center" label="定量下限(mg)">
        <template #default="{ row, $index }">
          <el-input
            v-model.number="row.dlxx"
            placeholder="定量下限"
            @input="$index === 0 ? (form.dlxx = row.dlxx) : onMinQuantInput(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样体积(L)">
        <template #default="{ row }">
          <el-input
            v-model="row.samplingVolume"
            placeholder="采样体积"
            @input="onMinQuantInput(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="最低定量浓度(mg/m³)">
        <template #default="{ row }">
          <el-input
            v-model="row.minQuantConcentration"
            placeholder="最低定量浓度"
            @input="onMinQuantConcentrationInput(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="80">
        <template #default="{ $index }">
          <el-button
            v-if="form.minQuantTable.length > 1"
            link
            size="small"
            type="danger"
            @click="removeMinQuantRow($index)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="minQuantDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveMinQuant">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import Facility from '@/views/infra/facility/facility.vue'
import { mergeWith } from 'lodash-es'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

const route = useRoute()
const router = useRouter()
const selectedFacility = ref<any>(null)
const loading = ref(false)
// form结构调整，testBasis默认值为[1,2]
const form = ref({
  sampleName: '滤膜',
  airCollector: '测尘滤膜',
  temperature: '25',
  humidity: '65',
  projectId: route.query.projectId,
  instrumentInfo: '',
  fmbzz: '0.05000',
  fmclz: '0.05000',
  submissionDate: '',
  testDate: '',
  dlxx: '',
  zddlld: '',
  testBasis: ['GBZ/ T 192.1-2007', 'GBZ/T 192.2-2007'],
  table: [
    {
      sampleNo: '',
      sampleVolume: '',
      cllmbh: '',
      quality: '',
      postWeight: '',
      weightIncrease: '',
      result: ''
    }
  ],
  minQuantTable: [{ dlxx: 0, samplingVolume: '', minQuantConcentration: '' }]
})
const facilityDialogVisible = ref(false)
const minQuantDialogVisible = ref(false)
// minQuantTable 已合并到 form

const openFacilityDialog = () => {
  facilityDialogVisible.value = true
}
const handleFacilitySelectionChange = (selection: any[]) => {
  const facility = Array.isArray(selection[0]) ? selection[0][0] : selection[0]
  selectedFacility.value = facility || null
}
const handleFacilityConfirm = () => {
  console.log('确认选择设备:', JSON.stringify(selectedFacility.value))
  if (selectedFacility.value) {
    form.value.dlxx=selectedFacility.value.dlxx
    form.value.instrumentInfo =
      selectedFacility.value.name +
      '/' +
      selectedFacility.value.model +
      '/' +
      selectedFacility.value.serialNumber
    console.log('选择设备form:', JSON.stringify(form.value))
    console.log('选择设备:', JSON.stringify(selectedFacility.value))
    facilityDialogVisible.value = false
    selectedFacility.value = null
    ElMessage.success('选择设备成功')
  } else {
    ElMessage.warning('请选择设备')
  }
}
const minimumQuantitativeConcentration = () => {
  minQuantDialogVisible.value = true
}
const addMinQuantRow = () => {
  form.value.minQuantTable.push({
    dlxx: form.value.dlxx,
    samplingVolume: '',
    minQuantConcentration: ''
  })
}
const removeMinQuantRow = (index: number) => {
  form.value.minQuantTable.splice(index, 1)
}
const saveMinQuant = () => {
  // 这里可以做保存逻辑，比如传给后端
  // 拼接zddlld
  form.value.zddlld = form.value.minQuantTable
    .filter((row) => row.minQuantConcentration && row.samplingVolume)
    .map((row) => `${row.minQuantConcentration}mg/m³ (采样体积为${row.samplingVolume}L时)`)
    .join('、')
  minQuantDialogVisible.value = false
  console.log('保存的minQuantTable:', JSON.stringify(form.value.minQuantTable))
  ElMessage.success('保存成功')
}
const getDefaultSampleHandoverRecord = async () => {
  const projectId = route.query.projectId as string
  const result = await ProjectApi.getDefaultAfterSample(Number(projectId))
  console.log('getDefaultSampleHandoverRecord result:', result)
  if (result && result.table) {
    form.value.table = result.table
  }
  // 获取返回的所有体积 去重从小到大排序
  const sampleVolumes = result.table
    .map((item) => parseFloat(item.sampleVolume)) // Convert to numbers
    .filter((volume) => !isNaN(volume)) // Filter out invalid numbers
    .sort((a, b) => a - b) // Sort numerically
    .filter((volume, index, array) => array.indexOf(volume) === index) // Remove duplicates

  console.log('Unique sorted sampleVolumes:', sampleVolumes)
  form.value.minQuantTable = []
  // 计算限制
  sampleVolumes.forEach((item) =>
    form.value.minQuantTable.push({
      dlxx: form.value.dlxx,
      samplingVolume: item,
      minQuantConcentration: ((form.value.dlxx / item) * 10000).toFixed(2)
    })
  )

  form.value.zddlld = form.value.minQuantTable
    .filter((row) => row.minQuantConcentration && row.samplingVolume)
    .map((row) => `${row.minQuantConcentration}mg/m³ (采样体积为${row.samplingVolume}L时)`)
    .join('、')
}
watch(
  form,
  async (newValue, oldValue) => {
    console.log('form changed:', JSON.stringify(newValue))
    // 在这里执行你的逻辑
    await ProjectApi.updateAfterSample(form.value)
    // if (!loading.value) {
    //   ElMessage.success('修改成功')
    // }
    loading.value = false
  },
  { deep: true } // 深度监听，因为 form 是嵌套对象
)

function customizer(objValue, srcValue) {
  // 如果源值是空值(null, undefined, '')，则保留目标值
  if (srcValue === null || srcValue === undefined || srcValue === '') {
    return objValue
  }
  // 对于数组，特殊处理
  if (Array.isArray(srcValue)) {
    return srcValue.length > 0 ? srcValue : objValue
  }
}

onMounted(async () => {
  loading.value = true
  const projectId = route.query.projectId as string
  const result = await ProjectApi.getAfterSample(Number(projectId))

  form.value = mergeWith({ ...form.value }, result, customizer)
})

// 头部按钮事件
const onSyncHeader = async () => {
  try {
    await ElMessageBox.confirm('已有数据将被覆盖，确认是否同步？', '确认同步', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  await getDefaultSampleHandoverRecord()
}
const onPreviewHeader = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 12
    }
  })
}

// 更新所有行的测定结果result字段
const updateAllResults = () => {
  form.value.table.forEach(row => {
    const val = getResultValue(row)
    row.result = val === undefined || val === null ? '' : String(val)
  })
}
// 自动计算滤膜增重
const onWeightInput = (row: any) => {
  const m1 = parseFloat(row.quality)
  const m2 = parseFloat(row.postWeight)
  if (!isNaN(m1) && !isNaN(m2)) {
    row.weightIncrease = (m2 - m1).toFixed(5)
  } else {
    row.weightIncrease = ''
  }
  updateAllResults()
}
// 采样后滤膜质量校验，必须大于等于采样前滤膜质量
const onPostWeightInput = (row: any, oldVal: string | number) => {
  const m1 = parseFloat(row.quality)
  const m2 = parseFloat(row.postWeight)
  if (!isNaN(m1) && !isNaN(m2) && m2 < m1) {
    ElMessage.warning({
      message: '采样后滤膜质量m₂(g)不能小于采样前滤膜质量m₁(g)，修改失败',
      duration: 5000 // 设置为 5000 毫秒（即 5 秒）
    });
    row.postWeight = oldVal
  } else {
    onWeightInput(row)
  }
  updateAllResults()
}
// 自动计算最低定量浓度
const onMinQuantInput = (row: any) => {
  const dlxx = parseFloat(row.dlxx)
  const samplingVolume = parseFloat(row.samplingVolume)
  if (!isNaN(dlxx) && !isNaN(samplingVolume) && samplingVolume !== 0) {
    row.minQuantConcentration = ((dlxx / samplingVolume) * 10000).toFixed(2)
  } else {
    row.minQuantConcentration = ''
  }
  updateAllResults()
}
// 弹窗表格：最低定量浓度和定量下限双向联动
const onMinQuantConcentrationInput = (row: any) => {
  const minQuantConcentration = parseFloat(String(row.minQuantConcentration))
  const samplingVolume = parseFloat(String(row.samplingVolume))
  if (!isNaN(minQuantConcentration) && !isNaN(samplingVolume) && samplingVolume !== 0) {
    row.dlxx = parseFloat(((minQuantConcentration * samplingVolume) / 10000).toFixed(2))
  } else {
    row.dlxx = 0
  }
  updateAllResults()
}

function formatDecimal(str) {
  if (!str) return str;
  const num = parseFloat(str);
  return isNaN(num) ? str : num.toFixed(2);
}


// 动态计算测定结果（mg/m³）
const getResultValue = (row: any) => {
  // 获取采样体积
  const samplingVolume = parseFloat(row.sampleVolume)
  // 获取滤膜增重
  const weightIncrease = parseFloat(row.weightIncrease)
  if (isNaN(samplingVolume)) return ''
  // 找到对应体积的minQuantConcentration
  const match = form.value.minQuantTable.find(item => Number(item.samplingVolume) === samplingVolume)
  const minQuant = match ? formatDecimal(match.minQuantConcentration) : undefined;
  if (minQuant === undefined || isNaN(weightIncrease)) return ''

  const result = parseFloat(((weightIncrease/samplingVolume)*1000000).toFixed(3))
  if (result>minQuant){
    return result
  }else {
    return '<'+minQuant
  }
}
// 在watch form.dlxx时也同步更新结果
watch(
  () => form.value.dlxx,
  (val) => {
    if (form.value.minQuantTable.length > 0) {
      form.value.minQuantTable.forEach((row) => {
        row.dlxx = val
        const dlxx = parseFloat(String(row.dlxx))
        const samplingVolume = parseFloat(String(row.samplingVolume))
        if (!isNaN(dlxx) && !isNaN(samplingVolume) && samplingVolume !== 0) {
          row.minQuantConcentration = ((dlxx / samplingVolume) * 10000).toFixed(2)
        } else {
          row.minQuantConcentration = ''
        }
      })
      // 同步zddlld
      form.value.zddlld = form.value.minQuantTable
        .filter((row) => row.minQuantConcentration && row.samplingVolume)
        .map((row) => `${row.minQuantConcentration}mg/m³ (采样体积为${row.samplingVolume}L时)`)
        .join('、')
    }
    updateAllResults()
  }
)
// 合并送检日期和检测日期的校验watch
let lastSubmissionDate = form.value.submissionDate
let lastTestDate = form.value.testDate
watch(
  [() => form.value.submissionDate, () => form.value.testDate],
  ([newSubmission, newTest], [oldSubmission, oldTest]) => {
    // 校验送检日期不能大于检测日期
    if (newSubmission && newTest && newSubmission > newTest) {
      if (newSubmission !== oldSubmission) {
        ElMessage.warning({
          message: '检测日期不能小于送检日期，修改失败',
          duration: 5000 // 设置为 5000 毫秒（即 5 秒）
        });
        form.value.submissionDate = lastSubmissionDate
      } else if (newTest !== oldTest) {
        ElMessage.warning({
          message: '检测日期不能小于送检日期，修改失败',
          duration: 5000 // 设置为 5000 毫秒（即 5 秒）
        });
        form.value.testDate = lastTestDate
      }
    } else {
      lastSubmissionDate = newSubmission
      lastTestDate = newTest
    }
  }
)
</script>

<style lang="scss" scoped>
.header-container-consumable {
  display: flex; // Use flex layout
  justify-content: space-between; // Space between title and button container
  align-items: center; // Vertically align items
  margin-bottom: 20px; // Add space below the header block
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.env-item {
  display: flex;
  align-items: center;
}

.centered-title-consumable {
  text-align: center; // Center the text inside this element
  flex-grow: 1; // Allow the title to take up available space
  margin: 0; // Reset default margin to correctly center
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
      // 表格输入内容居中
      .el-input__inner,
      .el-input-number__inner {
        text-align: center !important;
      }
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

// 输入对齐
//:deep(.el-input__inner) {
//  text-align: center;
//}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
